﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.Networking;
using Windows.Networking.Sockets;
using Windows.Storage.Streams;
using Windows.UI.Core;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;

// “空白页”项模板在 http://go.microsoft.com/fwlink/?LinkId=234238 上有介绍

namespace TabletSocket
{
    /// <summary>
    /// 可用于自身或导航至 Frame 内部的空白页。
    /// </summary>
    public sealed partial class MainPage : Page
    {
        //receive socket
        DatagramSocket receiveSocket=new DatagramSocket();

        //send socket
        DatagramSocket sendSocket;//=new DatagramSocket();
       
        //IOutputStream sendOutputStream;
        DataWriter sendWriter;
       
        public  MainPage()
        {
            this.InitializeComponent();
            createsocketserver();
        }
        public async void createsocketserver(){

            //DatagramSocket receiveSocket = new DatagramSocket();
            receiveSocket.MessageReceived += receiveSocket_MessageReceived;
            try
            {
                await receiveSocket.BindServiceNameAsync("22114");
                msgList.Children.Add(new TextBlock { Text = "监听成功", FontSize = 20 });
            }
            catch (Exception err)
            {
                if (SocketError.GetStatus(err.HResult) == SocketErrorStatus.AddressAlreadyInUse)
                {
                    // 异常消息，使用SocketErrorStatus枚举来判断Socket的异常类型
                }
            }
            
          
        }

        async void receiveSocket_MessageReceived(DatagramSocket sender, DatagramSocketMessageReceivedEventArgs args)
        {
            DataReader dataReader = args.GetDataReader();
            uint length = dataReader.UnconsumedBufferLength;
            string content = dataReader.ReadString(length);
            await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
            msgList2.Children.Add(new TextBlock { Text = "收到服务端的消息：" + content, FontSize = 20 }));
            switch (content)
            {
                   
                case "receive1":
                    await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                    msgList.Children.Add(new TextBlock { Text = "下单成功", FontSize = 20 }));     
                    break;
                case "1sure":
                    await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                    msgList.Children.Add(new TextBlock { Text = "收到确认订单消息", FontSize = 20 }));
                    await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                    msgList.Children.Add(new TextBlock { Text = "订单已确认", FontSize = 20 }));
                    sendmessage("1hassure");
                    await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                   msgList.Children.Add(new TextBlock { Text = "发送订单已确认的消息", FontSize = 20 })); 
                    break;
                   /*   
                case "receive2":
                    await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                    msgList.Children.Add(new TextBlock { Text = "下单成功", FontSize = 20 }));
                    break;
                case "2sure":
                    await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                    msgList.Children.Add(new TextBlock { Text = "收到确认订单消息", FontSize = 20 }));
                    await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                    msgList.Children.Add(new TextBlock { Text = "订单已确认", FontSize = 20 }));
                    sendmessage("2hassure");
                    await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                   msgList.Children.Add(new TextBlock { Text = "发送订单已确认的消息", FontSize = 20 }));
                    break;
                */
            }


            /*
            IOutputStream outputStream = await sender.GetOutputStreamAsync(
                  args.RemoteAddress,
                  args.RemotePort);
            DataWriter writer = new DataWriter(outputStream);
            writer.WriteString(content + "（服务器发送）");
            try
            {
                await writer.StoreAsync();
                await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                    msgList.Children.Add(new TextBlock { Text = "服务器发送的消息：" + content + "（服务器发送）", FontSize = 20 }));
            }
            catch (Exception err)
            {
                if (SocketError.GetStatus(err.HResult) == SocketErrorStatus.AddressAlreadyInUse)
                {
                    // 异常消息，使用SocketErrorStatus枚举来判断Socket的异常类型
                }
            }
            
           */
        }
       








        public async void sendmessage(string message){
            if (sendWriter == null)
            {
                if (sendSocket == null)
                {
                    HostName hostName = new HostName("192.168.1.255");
                    sendSocket = new DatagramSocket();
                    //sendSocket.MessageReceived += datagramSocket_MessageReceived2;
                    IOutputStream outputStream = await sendSocket.GetOutputStreamAsync(hostName, "22114");
                    sendWriter = new DataWriter(outputStream);
                }
                else
                {
                    sendWriter = new DataWriter(sendSocket.OutputStream);
                }
            }


            sendWriter.WriteString(message);
            try
            {
                await sendWriter.StoreAsync();
                msgList.Children.Add(new TextBlock { Text = "客户端：" + message+"下单", FontSize = 20 });
            }
            catch (Exception err)
            {
                if (SocketError.GetStatus(err.HResult) == SocketErrorStatus.AddressAlreadyInUse)
                {
                    // 异常消息，使用SocketErrorStatus枚举来判断Socket的异常类型
                }
            }
        }

        private void send_Click(object sender, RoutedEventArgs e)
        {
            sendmessage("1");

        }

        //关闭发送端
        private void close_Click(object sender, RoutedEventArgs e)
        {
            if (sendSocket != null)
            {
                sendSocket.Dispose();
                sendSocket = null;
            }
            if (sendWriter != null)
            {
                sendWriter.Dispose();
                sendWriter = null;
            }
        }

    }
}
